import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    if (exception instanceof HttpException) {
      const status = exception.getStatus();
      const res = exception.getResponse() as any;

      return response.status(status).json({
        code: res.code || status,
        msg: res.msg || res.message || '服务器内部异常!',
        data: res.data ?? null,
      });
    }

    // 未知错误
    return response.status(HttpStatus.INTERNAL_SERVER_ERROR).json({
      code: 500,
      msg: (exception as any).message || '服务器内部未知错误!',
      data: null,
    });
  }
}
